<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <div slot="header">
          <!-- 页面标题 pagesTitle -->
          <span>{{ pagesTitle }}</span>
        </div>

        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
          <!-- 学科 -->
          <el-form-item :label="$t('questionNew.subject')" prop="subjectID">
            <el-select
              style="width: 400px"
              v-model="ruleForm.subjectID"
              placeholder="请选择学科"
              @change="getDirectorySimpleList(ruleForm.subjectID)"
            >
              <!-- label的值是显示的标题; value的值是传递给v-model的 -->
              <!-- value是学科id, label是学科标题 -->
              <el-option :label="item.label" :value="item.value" v-for="item in subjectList" :key="item.value"></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item :label="$t('questionNew.catalogue')" prop="catalogID">
            <el-select
              placeholder="请选择目录"
              style="width: 400px"
              v-model="ruleForm.catalogID"
            >
              <el-option :label="item.directoryName" :value="item.id" v-for="item in directoryList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item :label="$t('questionNew.enterprise')" prop="enterpriseID">
            <el-select
              placeholder="请选择企业"
              style="width: 400px"
              v-model="ruleForm.enterpriseID"
              @click.native="getCompanyList"
            >
              <el-option :label="item.company" :value="item.id" v-for="item in companyList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-form-item :label="$t('questionNew.city')" prop="province">
            <el-select v-model="ruleForm.province" placeholder="请选择" style="width: 198px">
              <el-option :label="item" :value="item" v-for="(item,index) in provincesList" :key="index"></el-option>
            </el-select>

            <el-select
              placeholder="请选择"
              :class="{'el-select_city': true}"
              style="width: 198px"
              v-model="ruleForm.city"
              @click.native="getCity(ruleForm.province)"
            >
              <el-option :label="item" :value="item" v-for="(item,index) in citysList" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item :label="$t('questionNew.direction')" prop="direction">
            <el-select v-model="ruleForm.direction" placeholder="请选择方向" style="width: 400px">
              <el-option :label="item" :value="item" v-for="(item,index) in directionEnum" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item :label="$t('questionNew.questionType')" prop="questionType">
            <el-radio-group v-model="ruleForm.questionType">
              <el-radio label="1">单选</el-radio>
              <el-radio label="2">多选</el-radio>
              <el-radio label="3">简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item :label="$t('questionNew.difficulty')" prop="difficulty">
            <el-radio-group v-model="ruleForm.difficulty">
              <el-radio label="1">简单</el-radio>
              <el-radio label="2">一般</el-radio>
              <el-radio label="3">困难</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item :label="$t('questionNew.stem')" prop="question">
            <!-- 富文本编辑器 -->
            <!-- 问题: 规则+别人组件 失去焦点blur的时候, 没有进行校验 -->
            <!-- 解决: 人工进行blur时的校验 -->
            <quill-editor
              v-model="ruleForm.question"
              ref="myQuillEditor"
              :options="editorOption"
              @blur="onEditorQuestionBlur()"
            >
            </quill-editor>
          </el-form-item>

          <!-- 选项 -->
          <el-form-item :label="$t('questionNew.option')" v-show="ruleForm.questionType !== '3'">
            <div class="option_item" v-for="(item,index) in ruleForm.options" :key="item.key">
              <!-- 单选按钮 -->
              <el-radio-group v-model="item.isRight" v-show="ruleForm.questionType === '1'">
                <el-radio style="margin-right:0px" :label="true" @change="checkRadio(item)">{{transCode(index)}}：</el-radio>
              </el-radio-group>
              <!--复选框 -->
              <el-checkbox-group v-model="item.isRight" v-show="ruleForm.questionType === '2'" style="display: inline-block">
                <el-checkbox :label="true" >{{transCode(index)}}：</el-checkbox>
              </el-checkbox-group>
              <!-- input输入框 -->
              <el-input v-model="item.title" style="width: 240px" />
              <!-- 上传图片的控件 -->
              <div class="avatar-uploader" :class="{'disabled': item.fileList.length >= 1}">
                <el-upload
                  action="#"
                  :file-list="item.fileList"
                  list-type="picture-card"
                  :limit="limit"
                  :on-change="(file, fileList) => {return handleChange(file,fileList,index)}"
                  :on-remove="(file, fileList) => {return handleChange(file,fileList,index)}"
                  :http-request="httpRequest"
                >
                <span>上传图片</span>
                </el-upload>
              </div>
            </div>
          </el-form-item>

          <el-form-item v-show="ruleForm.questionType !== '3'">
            <el-button type="danger" :disabled="ruleForm.questionType !== '2'" @click="addOptions">+增加选项与答案</el-button>
          </el-form-item>

          <!-- 解析视频 -->
          <el-form-item :label="$t('questionNew.parseVideo')">
            <el-input v-model="ruleForm.videoURL" style="width: 400px" />
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item :label="$t('questionNew.answerAnalysis')" prop="answer">
            <quill-editor
              v-model="ruleForm.answer"
              ref="myQuillEditor"
              :options="editorOption"
              @blur="onEditorAnswerBlur()"
            >
            </quill-editor>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item :label="$t('questionNew.topicRemarks')">
            <!-- textarea默认高度为 :rows="2", 修改高度直接更改里面的数字即可 -->
            <el-input type="textarea" v-model="ruleForm.remarks" style="width: 400px;" :rows="4" />
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item :label="$t('questionNew.questionLabel')">
            <el-select
              placeholder="请选择试题标签"
              style="width: 400px"
              v-model="ruleForm.tags"
              multiple
            >
              <el-option :label="item.tagName" :value="item.tagName" v-for="item in tagsList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- 底部按钮 -->
          <el-form-item>
            <el-button ref="elbutton" :type="footerButtonColor ? 'success': 'primary'" @click="confirmSubmit">{{footerButtonTitle}}</el-button>
          </el-form-item>
        </el-form>

      </el-card>
    </div>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
// 引入方向(可遍历数据)
import { direction as directionEnum } from '@/api/hmmm/constants.js'
// 引入【学科简单列表api】学科列表
import { simple as getSubjectSimpleListApi } from '@/api/hmmm/subjects.js'
// 引入【目录列表api】
import { list as getDirectoryListApi } from '@/api/hmmm/directorys.js'
// 引入【企业列表api】
import { list as getCompanyListApi } from '@/api/hmmm/companys.js'
// 引入【城市 城市下地区】
import { provinces as getProvinces, citys as getCitys } from '@/api/hmmm/citys.js'
// 引入【标签列表api】
import { list as getTagsListApi } from '@/api/hmmm/tags.js'
// 引入【基础题库添加api】【基础题库详情api】【基础题库修改api】
import { add as addBasicQuestionApi, detail as getBasicQuestionDetailApi, update as updateBasicQuestionApi } from '@/api/hmmm/questions.js'

import cos from '@/utils/cos.js'
export default {
  name: 'questionsNew',
  components: {
    quillEditor
  },
  data () {
    return {
      // 页面头部标题
      pagesTitle: this.$t('questionNew.title1'), // '试题录入',
      // 页面底部按钮文字
      footerButtonTitle: this.$t('questionNew.footButton1'), // '确认提交',
      // 基础题库 路由题库跳转过来的时候的id值
      routerID: '',
      // 底部按钮颜色
      footerButtonColor: false,
      ruleForm: {
        subjectID: '', // 学科ID
        catalogID: '', // 目录ID
        enterpriseID: '', // 企业ID
        province: '', // 省份
        city: '', // 城市
        direction: '', // 方向
        questionType: '1', // 题型 1:单选 2:多选 3:简答
        difficulty: '1', // 难度 1:简单 2:一般 3:困难
        question: '', // 题干
        videoURL: '', // 解析视频(不需要校验)
        answer: '', // 答案解析
        remarks: '', // 题目备注(不需要校验)
        tags: '', // 试题标签(不需要校验)
        options: [
          // code:单选/复选框的名字 img:图片路径 isRight:是否选这一项 Boolean title:input框里面的内容
          { code: 'A', img: '', isRight: false, title: '', fileList: [] },
          { code: 'B', img: '', isRight: false, title: '', fileList: [] },
          { code: 'C', img: '', isRight: false, title: '', fileList: [] },
          { code: 'D', img: '', isRight: false, title: '', fileList: [] }
        ]

      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '题干内容不能为空', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '答案解析内容不能为空', trigger: 'blur' }
        ]
      },
      // 富文本编辑器配置项
      editorOption: {
        placeholder: '',
        modules: {
          // toolbar: 工具栏相关配置
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表，无序列表
            ['link', 'image', 'upload', 'video'] // 上传图片、上传视频
          ]
        }
      },
      // 方向可遍历数组
      directionEnum,
      // 学科列表
      subjectList: [],
      // 目录列表
      directoryList: [],
      // 企业列表
      companyList: [],
      provincesList: [],
      citysList: [],
      // 试题标签列表
      tagsList: [],
      // 用来存储组件
      componentsList: [],
      limit: 1
    }
  },
  watch: {
    // 侦听路由信息的变化
    $route: {
      immediate: true,
      deep: true,
      handler (newVal, oldVal) {
        this.routerChange()
      }
    }
  },
  created () {
    this.getSubjectSimpleList()
    this.provincesList = getProvinces()
  },
  methods: {
    /**
     * 从【基础题库】【精选题库】跳转过来后页面对应变化
     */
    async routerChange () {
      // 用传递过来的id发送请求 进行数据回显
      this.routerID = this.$route.query.id
      if (this.routerID) {
        this.pagesTitle = this.$t('questionNew.title2') // '试题修改'
        this.footerButtonTitle = this.$t('questionNew.footButton2') // '确认修改'
        this.footerButtonColor = true
        const res = await getBasicQuestionDetailApi({ id: this.routerID })
        console.log('33333', res.data)
        // 试题标签由字符串改为数组
        res.data.tags = res.data.tags.split(',')
        res.data.options.forEach(i => {
          // 把单选或单选的标志改成true或false
          if (i.isRight === 0) {
            i.isRight = false
          } else {
            i.isRight = true
          }
          // 图片回显
          i.fileList = []
          if (i.img) {
            i.fileList.push({ url: i.img })
            console.log(i.img)
          }
        })
        this.ruleForm = res.data
        console.log('this.ruleForm', this.ruleForm)
      }
    },
    /**
     * ASCII码值转换为字符的方法
     */
    transCode (ASCIIcode) {
      return String.fromCharCode(+ASCIIcode + 65)
    },
    /**
     * 选项模块单选按钮【排他思想】
     */
    checkRadio (item) {
      this.ruleForm.options.forEach(i => { i.isRight = false })
      item.isRight = true
    },

    /**
     * file：表示的上传的数据
     * fileList: 表示的DOM元素中对应的数据
     */
    handleChange (file, fileList, i) {
      // i就是拿到的索引值
      // console.log('iiiiiii', i)
      this.ruleForm.options[i].fileList = [...fileList]
      // console.log(this.ruleForm.options)
    },

    handleRemove (file, fileList, i) {
      this.ruleForm.options[i].fileList = []
    },
    /**
     * 图片自定义上传
     */
    httpRequest ({ file }) {
      if (!file) return
      // console.log('filefilefile', file)
      // 拿到当前上传的文件
      const currentFileList = this.ruleForm.options.filter(i => {
        const fileObj = i.fileList[0]
        if (fileObj) {
          return i.fileList[0].uid === file.uid
        }
      })
      const currentFile = currentFileList[0].fileList[0]
      // console.log('currentFile', currentFile)
      // 将上传状态设置为 'uploading'
      currentFile.status = 'uploading'
      cos.putObject({
        Bucket: 'hrsass-152-1316190622', /* 填入您自己的存储桶，必须字段 (自己的存储桶的名字) */
        Region: 'ap-beijing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: +new Date() + file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        Body: file, /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */
        onProgress: function (progressData) {
          console.log(JSON.stringify(progressData))
          // 显示上传的百分比进度
          currentFile.percentage = progressData.percent * 100
        }
      }, function (err, data) {
        // console.log(err || data)
        if (err) {
          this.$message.warning('图片上传失败, 请稍后再试')
          return
        }
        // 使用'//' 会自动把网站对应的协议和地址拼接到一起
        const url = '//' + data.Location
        currentFile.url = url
        // 延时目的: 可以更清楚的看到进度条的加载
        // setTimeout(() => {
        currentFile.status = 'success'
        // }, 500)
      })
    },
    /**
     * 题干校验
     */
    onEditorQuestionBlur () {
      // 1. el-form下规则 单独对 question这项进行校验
      // 2. el-form上找到单独校验方法
      this.$refs.ruleForm.validateField('question')
    },
    /**
     * 答案解析校验
     */
    onEditorAnswerBlur () {
      this.$refs.ruleForm.validateField('answer')
    },
    /**
     * 获取学科简单列表
     */
    async getSubjectSimpleList () {
      const { data } = await getSubjectSimpleListApi()
      // console.log('bbbbb', data) // 返回的value值是id, label是标题
      this.subjectList = data
    },

    /**
     * 获取目录和标签
     */
    async getDirectorySimpleList (id) {
      // 每次发请求之前将目录和标签置空
      this.ruleForm.catalogID = ''
      this.ruleForm.tags = ''
      const res = await getDirectoryListApi({ subjectId: id, page: 1, pagesize: 9999 })
      // console.log('ccc', res)
      this.directoryList = res.data.items.filter(item => item.subjectID === +id)
      // console.log(this.directoryList)
      const res2 = await getTagsListApi({ subjectId: id, page: 1, pagesize: 9999 })
      console.log('res2', res2)
      this.tagsList = res2.data.items.filter(item => item.subjectID === +id)
    },

    /**
     * 获取企业列表
     */
    async getCompanyList () {
      const { data: { items } } = await getCompanyListApi({ pagesize: 9999 })
      // console.log('aaaaaaaaa', items)
      this.companyList = items
    },

    /**
     * 获取城市下地区数据
     */
    getCity (pname) {
      this.citysList = getCitys(pname)
    },

    /**
     * 动态添加选项模块
     */
    addOptions () {
      const long = this.ruleForm.options.length
      if (long >= 62) {
        return
      }
      this.ruleForm.options.push(
        {
          code: this.transCode(long),
          img: '',
          isRight: false,
          title: '',
          fileList: [],
          key: Date.now()
        }
      )
      console.log('OPTIONS', this.ruleForm.options)
    },

    /**
     * 确认提交按钮对应的业务逻辑
     */
    confirmSubmit () {
      this.$refs.ruleForm.validate(async flag => {
        if (!flag) return
        // 判断添加试题还是修改试题
        if (this.routerID) {
          // 修改业务
          this.ruleForm.options.forEach(i => {
            delete i.fileList
          })
          await updateBasicQuestionApi(this.ruleForm)
          this.$message.success('修改成功')
          // 将路由传递归来的id清空 把按钮颜色再改回来
          this.routerID = ''
          this.footerButtonColor = false
          this.pagesTitle = this.$t('questionNew.title1') // '试题录入'
          this.footerButtonTitle = this.$t('questionNew.footButton1') // '确认提交'
        } else {
          // 添加业务
          // 将tags数组转换为字符串
          this.ruleForm.tags = this.ruleForm.tags.join(',') || ''
          // 对options数组进行转换
          this.ruleForm.options.forEach(i => {
            if (i.fileList.length > 0) {
              i.img = i.fileList[0].url
            }
            delete i.fileList
          })
          await addBasicQuestionApi(this.ruleForm)
          // console.log('mmmmm', res)
          this.$message.success('添加成功')
        }
        this.$router.push('/questions/list')
        console.log(this.ruleForm)
      })
    }
  }
}
</script>

<style scoped lang="scss">
.el-select_city {
  margin-left: 4px;
}
// 设置富文本编辑器的高度
::v-deep .ql-container {
  height: 200px;
}
// 上传图片的样式
.option_item {
  margin-bottom: 20px;
  .avatar-uploader {
    margin-left:4px;
    display: inline-block;
    position: relative;
    ::v-deep .el-upload--picture-card {
      width: 100px;
      height: 60px;
      line-height: 60px;
      vertical-align: middle;
    }
    ::v-deep .el-upload-list__item-actions {
      width: 100px;
      height: 60px;
      border-radius: 6px;
    }
    ::v-deep .el-upload-list--picture-card .el-upload-list__item {
      width: 100px;
      height: 60px;
      border-radius: 6px;
      vertical-align: middle;
    }
  }
  // 控制上传图片组件的显示隐藏
  .disabled {
    ::v-deep{
      .el-upload--picture-card{
        // display: none;
        visibility: hidden;
      }
    }
  }
}
</style>
